<template>
  <div class="pane-account">
    <el-form ref="formRel" :model="account" :rules="accountRules" label-width="60px" size="large">
      <el-form-item label="账号" prop="username">
        <el-input v-model="account.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
// 账号登录
import { reactive, ref } from 'vue'
import type { ElForm, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import useLoginStore from '@/store/login/login'
import { localCache } from '@/utils/cache'

const CACHE_NAME = 'username'
const CACHE_PASSWORD = 'password'
const account = reactive({
  username: localCache.getCache(CACHE_NAME) ?? '',
  password: localCache.getCache(CACHE_PASSWORD) ?? ''
})

// 为当前页面新增对应的校验集合
const accountRules: FormRules = {
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { pattern: /^[a-z0-9]{4,20}$/, message: '请输入6~20位的账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,}$/, message: '请输入三位以上的密码', trigger: 'blur' }
  ]
}

/**
 * 账号登录逻辑
 */
const formRel = ref<InstanceType<typeof ElForm>>()
const loginStore = useLoginStore()

function loginAction(isRemPwd: boolean) {
  formRel.value?.validate((validate) => {
    if (validate) {
      // 校验成功
      console.log('校验成功')
      const username = account.username
      const password = account.password
      loginStore.loginAccountAction({ username, password })
      // 3.判断是否需要记住密码
      if (isRemPwd) {
        localCache.setCache(CACHE_NAME, username)
        localCache.setCache(CACHE_PASSWORD, password)
      } else {
        localCache.removeCache(CACHE_NAME)
        localCache.removeCache(CACHE_PASSWORD)
      }
    } else {
      // 校验失败
      ElMessage.error('请输入正确格式的账号密码在进行登录操作')
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style lang="less" scoped></style>
